<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="报告名称" prop="reportName">
        <el-input
          v-model="queryParams.reportName"
          placeholder="请输入报告名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="fetchData"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择开始时间"
        />
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker
          v-model="queryParams.endTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择结束时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="deleteReport"
          v-hasPermi="['system:report:removeReport']"
        >批量删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="报告名称" align="center" prop="reportName" :show-overflow-tooltip="true" />
      <el-table-column label="总评结果" align="center" prop="evaluationResult" :show-overflow-tooltip="true" />
      <el-table-column label="评估方式" align="center" prop="evaluationName" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" /> -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="evaluationDate"
        width="180"
        :show-overflow-tooltip="true"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="exportReport(scope.row)"
            v-hasPermi="['system:report:exportReportInfoToWord']"
          >导出</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="viewReport(scope.row)"
            v-hasPermi="['system:report:getReportInfo']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗：用来显示报告详细信息 -->
    <el-dialog :visible.sync="dialogVisible" title="详细信息" width="60%">
      <div class="detail-section">
        <h3>标准信息</h3>
        <div class="detail-item"><strong>标准号：</strong>{{ standardInfo.standardCode }}</div>
        <div class="detail-item"><strong>标准名称：</strong>{{ standardInfo.standardName }}</div>
        <div class="detail-item"><strong>标准分类号：</strong>{{ standardInfo.classificationCode }}</div>
        <div class="detail-item"><strong>指定组织：</strong>{{ standardInfo.organization }}</div>
        <el-divider></el-divider>

        <h3>指标信息</h3>
        <div class="detail-item"><strong>总评得分：</strong>{{ resultInfo.outputValue }}</div>
        <div class="detail-item"><strong>指标体系：</strong>{{ resultInfo.projectName }}</div>
        <div class="detail-item"><strong>评估时间：</strong>{{ resultInfo.evaluateDate }}</div>
        <el-divider></el-divider>

        <h4>指标权重</h4>
        <el-table :data="indicatorScores" style="margin-bottom: 20px;">
          <el-table-column prop="indicatorName" label="指标名称" />
          <el-table-column prop="combinationWeight" label="权重" />
        </el-table>

        <h4>指标得分</h4>
        <el-table :data="indicatorScores">
          <el-table-column prop="indicatorName" label="指标名称" />
          <el-table-column prop="indicatorValue" label="得分" />
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">关闭</el-button>
    </span>
    </el-dialog>

    <!--分页-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handlePagination"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--        <el-form-item label="字典名称" prop="dictName">-->
        <!--          <el-input v-model="form.dictName" placeholder="请输入字典名称" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="字典类型" prop="dictType">-->
        <!--          <el-input v-model="form.dictType" placeholder="请输入字典类型" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="状态" prop="status">-->
        <!--          <el-radio-group v-model="form.status">-->
        <!--            <el-radio-->
        <!--              v-for="dict in dict.type.sys_normal_disable"-->
        <!--              :key="dict.value"-->
        <!--              :label="dict.value"-->
        <!--            >{{dict.label}}</el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="备注" prop="remark">-->
        <!--          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="选择数据类型" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="数据类型"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMenu, getMenu, delMenu, addMenu, updateMenu } from "@/api/system/menu";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
import { fetchReportList } from '@/api/report/report';
import {exportReport} from "@/api/report/report";
import {deleteReports} from "@/api/report/report";
import {getReportDetail} from "@/api/report/report";
import pagination from "@/components/Pagination/index.vue";

export default {
  name: "index",
  dicts: ['sys_show_hide', 'sys_normal_disable'],
  components: { Treeselect, IconSelect ,pagination},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "提示框",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        menuName: undefined,
        visible: undefined,
        reportName:'',
        startTime:'',
        endTime:'',
        pageSize:5,
        pageNum:1
      },
      // 表单参数
      form: {},

      // 报告列表
      dataList:[],

      //存储被选中项
      selectedRows:[],

      //报告详细信息
      standardInfo:{},
      resultInfo:{},
      indicatorScores:[],

      //弹窗状态
      dialogVisible:false,

      //分页总数据
      total:0,
      // 表单校验
      rules: {
        menuName: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" }
        ],
        path: [
          { required: true, message: "路由地址不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    // this.getList();
    this.fetchData();
  },
  methods: {

    //日期函数
    formatDate(row, column, cellValue, index) {
      if (!cellValue) return '';
      let date = new Date(cellValue);
      let year = date.getFullYear();
      let month = (date.getMonth() + 1).toString().padStart(2, '0');
      let day = date.getDate().toString().padStart(2, '0');
      let hours = date.getHours().toString().padStart(2, '0');
      let minutes = date.getMinutes().toString().padStart(2, '0');
      let seconds = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    //查看报告
    viewReport(row){
      getReportDetail(row.id)
        .then(response =>{
          console.log("报告详细信息response:",response);
          this.standardInfo=response.data.standard;
          this.resultInfo=response.data.result;
          this.indicatorScores=response.data.indicatorScores;
          this.dialogVisible=true;//显示弹窗
        })
        .catch(error =>{
          console.error('获取报告详细信息出错：',error)
        })
    },
    //存储选中项
    handleSelectionChange(val){
      this.selectedRows=val;
    },
    //删除报告
    deleteReport(){
      if (this.selectedRows.length === 0) {
        this.$message.warning("请先选择要删除的项");
        return;
      }
      this.$modal.confirm('是否确认删除选中的所有项？').then(() => {
        const ids = this.selectedRows.map(row => row.id);
        console.log("要删除id集合：",ids)
        return deleteReports(ids);
      }).then(() => {
        this.fetchData();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    //导出报告

    exportReport(row){
      exportReport(row.id)
        .then(response =>{
          // 创建一个 Blob 对象，用于处理二进制数据
          const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
          console.log("导出报告response:",response);
          // 创建一个 URL，用于 Blob 对象
          const url = window.URL.createObjectURL(blob);
          // 创建一个临时的 a 元素
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', 'report.docx'); // 指定下载的文件名
          // 将链接添加到页面中
          document.body.appendChild(link);
          // 模拟点击，触发下载
          link.click();
          // 下载完成后将链接从页面中移除
          document.body.removeChild(link);
          // 释放 Blob 对象的 URL
          window.URL.revokeObjectURL(url);
        })
        .catch(error => {
          console.error('导出报告时出错:', error);
        })
    },

    // 获取报告列表
    fetchData(){
      console.log('参数传递',this.queryParams)
      fetchReportList(this.queryParams)
        .then(response => {
          console.log('API response',response)
          if (response.code === 200) {
            this.dataList = response.rows;
            this.total=response.total;
          } else {
            this.$message.error(response.msg);
          }
          this.loading = false;
        })
        .catch(error => {
          console.error('Error fetching data:', error);
          this.loading = false;
        });
    },

    // 选择图标
    selected(name) {
      this.form.icon = name;
    },

    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      listMenu(this.queryParams).then(response => {
        this.menuList = this.handleTree(response.data, "menuId");
        this.loading = false;
      });
    },

    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      };
    },

    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listMenu().then(response => {
        this.menuOptions = [];
        const menu = { menuId: 0, menuName: '主类目', children: [] };
        menu.children = this.handleTree(response.data, "menuId");
        this.menuOptions.push(menu);
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        menuId: undefined,
        parentId: 0,
        menuName: undefined,
        icon: undefined,
        menuType: "M",
        orderNum: undefined,
        isFrame: "1",
        isCache: "0",
        visible: "0",
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    // handleQuery() {
    //   this.getList();
    // },

    /** 重置搜索 */
    resetQuery() {
      this.queryParams={
        menuName: undefined,
        visible: undefined,
        reportName:'',
        startTime:'',
        endTime:'',
        pageSize:5,
        pageNum:1
      }
      this.fetchData()
    },

    //处理分页函数
    handlePagination(pagination) {
      this.queryParams.pageNum = pagination.page;
      this.queryParams.pageSize = pagination.limit;
      this.fetchData();
    },

    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.menuId) {
        this.form.parentId = row.menuId;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加菜单";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      getMenu(row.menuId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改菜单";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.menuId != undefined) {
            updateMenu(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMenu(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

  }
}
</script>

<style scoped>
h3 {
  font-size: 1.5em;
  margin-top: 20px;
  margin-bottom: 10px;
  font-weight: bold;
}

h4 {
  font-size: 1.2em;
  margin-top: 15px;
  margin-bottom: 5px;
  font-weight: bold;
}

.detail-section {
  padding: 10px;
}

.detail-item {
  font-size: 1em;
  line-height: 1.5;
  color: #333;
  margin: 5px 0;
}

.detail-item strong {
  color: #000;
}

.dialog-footer {
  text-align: right;
}


</style>
